#!/bin/bash

# 创建证据目录
mkdir -p evidence

# 设置基本参数
BASE="http://localhost:3000"
TOKEN="$(cat backend/scripts/token.txt)"

# 1) 导出提交前的数据库状态
echo "1. 导出提交前的数据库状态"
node -e "const { query } = require('./backend/src/config/database'); (async () => { try { const menuItems = await query('SELECT id, name, name_en, updated_at FROM menu_items'); console.log(JSON.stringify(menuItems, null, 2)); } catch (err) { console.error(err); } })();" > evidence/db_before.json

# 2) 上传校验
echo "\n2. 上传校验测试"
curl -sS -X POST "$BASE/api/admin/menu-import/v2/validate" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@backend/menu_template.xlsx" | tee evidence/validate.json

jq -r .job_id evidence/validate.json   # ← 必须输出一个 job_id
JOB=$(jq -r .job_id evidence/validate.json)
echo "获取到job_id: $JOB"

# 3) 轮询状态（最多 30s）
echo "\n3. 轮询状态测试"
for i in {1..40}; do
  curl -sS "$BASE/api/admin/menu-import/v2/jobs/$JOB" -H "Authorization: Bearer $TOKEN" \
  | tee "evidence/job_$i.json"
  STATUS=$(jq -r .job.status "evidence/job_$i.json"); echo "poll#$i $STATUS"
  [[ "$STATUS" == "validated" || "$STATUS" == "failed" ]] && break
  sleep 0.8
done

# 4) 提交导入
echo "\n4. 提交导入测试"
curl -sS -X POST "$BASE/api/admin/menu-import/v2/commit?job_id=$JOB" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"idempotency_key\":\"$JOB\"}" | tee evidence/commit.json

# 5) 导出提交后的数据库状态
echo "\n5. 导出提交后的数据库状态"
sleep 2  # 等待数据库更新
node -e "const { query } = require('./backend/src/config/database'); (async () => { try { const menuItems = await query('SELECT id, name, name_en, updated_at FROM menu_items'); console.log(JSON.stringify(menuItems, null, 2)); } catch (err) { console.error(err); } })();" > evidence/db_after.json

# 6) 生成diff文件
echo "\n6. 生成diff文件"
diff -u evidence/db_before.json evidence/db_after.json > evidence/diff.txt || true

echo "\n数据库差异检查完成，结果已保存到evidence/diff.txt"
cat evidence/diff.txt